var Baidu_AK = "hXnV5CqM8Dcv99PqBUgIVrnwKCQMb9LR";

var ajaxs = function (url, type, param, async, successfuction, dataType, errorMsg, contentType) {
    /*var dt = '';
     if(typeof(dataType) == "undefined" || dataType == '') {
     dt = "json";
     }*/
    if (typeof (contentType) == "undefined" || contentType == '') {
        contentType = "application/x-www-form-urlencoded";
    }

    $.ajax({
        url: url,
        data: param,
        type: type,
        async: async,
        // dataType : dt,
        contentType: contentType,
        success: function (data) {
            if (typeof (successfuction) == "undefined" || successfuction == '') {
                return;
            }
            successfuction(data);
        },
        error: function (XMLHttpReques, massage, errorObject) {
            if (typeof (errorMsg) == "undefined" || errorMsg == '') {
                return;
            }
            layer.alert('失败', {skin: '"layui-bg-red'});
        }
    });
}

/**
 * @Title:LODOP使用指定打印机打印
 * @Author: 沈明可
 * @Param:
 * @return:
 * @CreateData: 2018/10/23  20:32
 **/
function printerLODOP(printerType, title, id, callback) {
    var printerTypeName = "";
    var printerName = "";
    ajaxs('./dictionary/printerType?printerType=' + printerType, 'GET', null, false, function (data) {
        printerTypeName = data.Type;
        printerName = data.Name;
    });
    var LODOP = getLodop();
    var printinit = LODOP.PRINT_INIT(title);
    var setprinterindex = LODOP.SET_PRINTER_INDEX(printerTypeName);
    if (setprinterindex) {
        if (printinit) {
            LODOP.ADD_PRINT_HTM(0, 0, "210mm", "297mm", document.getElementById(id).innerHTML);
            var print = LODOP.PRINT();
            layer.msg("正在打印 请稍等;")
            if (print) {
                layer.msg("打印成功");
                if (typeof (callback) != "undefined") {
                    callback();
                }
            } else {
                layer.msg("打印失败");
            }
        } else {
            layer.msg("打印机初始化失败 请重试;")
        }
    } else {
        layer.msg("请检查你的" + printerName + '是否连接以及' + printerName + '名称;');
    }
}

/**
 * @Title:LODOP使用指定打印机打印多个运单
 * @Author: 沈明可
 * @Param:
 * @return:
 * @CreateData: 2018/10/25  17:47
 **/
function printerLODOPMultiple(printerType, title, ids, callback) {
    var printerTypeName = "";
    var printerName = "";
    ajaxs('./dictionary/printerType?printerType=' + printerType, 'GET', null, false, function (data) {
        printerTypeName = data.Type;
        printerName = data.Name;
    });
    var LODOP = getLodop();
    var printinit = LODOP.PRINT_INIT(title);
    var setprinterindex = LODOP.SET_PRINTER_INDEX(printerTypeName);
    if (setprinterindex) {
        if (printinit) {
            for (var i = 0; i < ids.length; i++) {
                LODOP.PRINT_INIT(title);
                LODOP.SET_PRINTER_INDEX(printerTypeName);
                LODOP.SET_PRINT_PAGESIZE(1, "72mm", "120mm", "CreateCustomPage");
                LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", document.getElementById(ids[i]).innerHTML);
                //288
                var print = LODOP.PRINT();
                layer.msg("正在打印 请稍等;")
                if (print) {
                    layer.msg("打印成功");
                    if (typeof (callback) != "undefined") {
                        callback();
                    }
                } else {
                    layer.msg("打印失败");
                }
            }
        } else {
            layer.msg("打印机初始化失败 请重试;")
        }
    } else {
        layer.msg("请检查你的" + printerName + '是否连接以及' + printerName + '名称;');
    }
}

function printerTest(printerType, title, ids, callback) {
    var printerTypeName = "";
    var printerName = "";
    ajaxs('./dictionary/printerType?printerType=' + printerType, 'GET', null, false, function (data) {
        printerTypeName = data.Type;
        printerName = data.Name;
    });
    var LODOP = getLodop();
    var printinit = LODOP.PRINT_INIT(title);
    var setprinterindex = LODOP.SET_PRINTER_INDEX(printerTypeName);
    if (setprinterindex) {
        if (printinit) {
            for (var i = 0; i < ids.length; i++) {
                LODOP.PRINT_INIT(title);
                LODOP.SET_PRINTER_INDEX(printerTypeName);
                LODOP.SET_PRINT_PAGESIZE(1, "75mm", "300mm", "CreateCustomPage");
                LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", document.getElementById(ids[i]).innerHTML);
                //288
                var print = LODOP.PRINT();
                layer.msg("正在打印 请稍等;")
                if (print) {
                    layer.msg("打印成功");
                    if (typeof (callback) != "undefined") {
                        callback();
                    }
                } else {
                    layer.msg("打印失败");
                }
            }
        } else {
            layer.msg("打印机初始化失败 请重试;")
        }
    } else {
        layer.msg("请检查你的" + printerName + '是否连接以及' + printerName + '名称;');
    }
}

/**
 * @Title:打印多个标签
 * @Author: 沈明可
 * @Param:
 * @return:
 * @CreateData: 2018/10/25  19:39
 * */
function printerLODOPLableMultiple(printerType, title, ids, callback) {
    var printerTypeName = "";
    var printerName = "";
    ajaxs('./dictionary/printerType?printerType=' + printerType, 'GET', null, false, function (data) {
        printerTypeName = data.Type;
        printerName = data.Name;
    });
    var LODOP = getLodop();
    var printinit = LODOP.PRINT_INIT(title);
    var setprinterindex = LODOP.SET_PRINTER_INDEX(printerTypeName);
    if (setprinterindex) {
        if (printinit) {
            for (var i = 0; i < ids.length; i++) {
                LODOP.PRINT_INIT(title);
                LODOP.SET_PRINTER_INDEX(printerTypeName);
                LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", document.getElementById(ids[i]).innerHTML);
                //288
                var print = LODOP.PRINT();
                layer.msg("正在打印 请稍等;")
                if (print) {
                    layer.msg("打印成功");
                } else {
                    layer.msg("打印失败");
                }
            }
            if (typeof (callback) != "undefined") {
                callback();
            }
        } else {
            layer.msg("打印机初始化失败 请重试;")
        }
    } else {
        layer.msg("请检查你的" + printerName + '是否连接以及' + printerName + '名称;');
    }
}

/**
 * select2动态搜索数据及回显
 * @param dom
 * @param url
 * @param multiple
 * @param placeable
 */
function initSelect2(dom, url, multiple, placeable) {
    var flag = true;
    if (typeof (placeable) != "undefined") {
        flag = false;
    }
    var subject = $(dom);//元素
    var Select2 = subject.select2({
        ajax: {
            url: url,
            dataType: 'json',
            data: function (params) {
                return {
                    name: params.term // 搜索参数
                };
            },
            processResults: function (data, params) {
                for (var i = 0; i < data.length; i++) {
                    data[i].id = data[i].id;
                    data[i].text = data[i].name;
                }
                return {
                    results: data
                };
            },
            cache: true
        },
        placeholder: flag ? "请输入名称搜索" : placeable,
        allowClear: true,    //选中之后，可手动点击删除
        escapeMarkup: function (markup) {
            return markup;
        }, // 让template的html显示效果，否则输出代码
        minimumInputLength: 1,    //搜索框至少要输入的长度，此处设置后需输入才显示结果
        language: "zh-CN",         //中文
        multiple: multiple, //是否多选
        // maximumSelectionLength: 1,//最多能够选择的个数(后期此处可以用作单选select2的美化)
        width: '100%',
        theme: "classic",
        // closeOnSelect:false,
        templateResult: formatSubject, // 自定义下拉选项的样式模板
        templateSelection: formatSubjectSelection     // 自定义选中选项的样式模板
    });
    return Select2;
};

function formatSubject(item) {
    if (item.loading) return item;
    var markup = '<div> <p style="color: black" class="text-primary">' + item.name || item.text + '</p>';
    //markup += '这里可以添加其他选项...';
    markup += ' </div>';
    return markup;
}

function formatSubjectSelection(item) {
    return item.name || item.text;
}

//select2回显数据
function echoSelect2(dom, value) {
    $.each(value, function (index, value) {
        $(dom).append(new Option(value.name, value.id, false, true));
    });
    $(dom).trigger("change");
}

function getBasePath() {
    var location = (window.location + '').split('/');
    var basePath = location[0] + '//' + location[2] + '/' + location[3];
    return basePath;
}

String.prototype.startWith = function (str) {
    if (str == null || str == "" || this.length == 0 || str.length > this.length)
        return false;
    if (this.substr(0, str.length) == str)
        return true;
    else
        return false;
    return true;
}

String.prototype.endWith = function (str) {
    if (str == null || str == "" || this.length == 0 || str.length > this.length)
        return false;
    if (this.substring(this.length - str.length) == str)
        return true;
    else
        return false;
    return true;
}

Date.prototype.Format = function (formatStr) {
    var str = formatStr;
    var Week = ['日', '一', '二', '三', '四', '五', '六'];

    str = str.replace(/yyyy|YYYY/, this.getFullYear());
    str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));

    str = str.replace(/MM/, this.getMonth() > 8 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
    str = str.replace(/M/g, this.getMonth() + 1);

    str = str.replace(/w|W/g, Week[this.getDay()]);

    str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
    str = str.replace(/d|D/g, this.getDate());

    str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
    str = str.replace(/h|H/g, this.getHours());
    str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
    str = str.replace(/m/g, this.getMinutes());

    str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
    str = str.replace(/s|S/g, this.getSeconds());

    return str;
}

$.CloseFormDialog = function() {
	$("#im_unique_dlg").hide();
}

$.FormDialog = function (option) {
    var defaultOpt = {
        form_url: '',
        id: 0,
        title: '',
        save_btn: {show: true, txt: '保存'},
        close_btn: {show: true, txt: '关闭'},
        e_btn: [],          //额外的btn，可选{txt:'123,action:'functionname'}
        callback: null,     //保存成功后的回调函数
        fullscreen: false,
        isclose: false,
        width: '500px'
    }

    var _opt = $.extend({}, defaultOpt, option);

    var init = function () {
        var wdth = _opt.fullscreen ? ' style="width:100%"' : ' style="width:' + _opt.width + '"';
        var htm = '<div class="modal fade" id="im_unique_dlg" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
            '<div class="modal-dialog" ' + wdth + '>' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +
            '<h4 class="modal-title" id="myModalLabel">' + _opt.title + '</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            '</div>' +
            '<div class="modal-footer">' +
            (_opt.close_btn.show ? '<button type="button" class="btn btn-default" data-dismiss="modal">' + _opt.close_btn.txt + '</button>' : '') +
            (_opt.save_btn.show ? '<button save type="button" class="btn btn-primary">' + _opt.save_btn.txt + '</button>' : '') +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        $(".form-dialog").html(htm);
        //渲染自定义按钮
        if (!_opt.e_btn) {
            return;
        }
        if (Object.prototype.toString.call(_opt.e_btn) == '[object Array]') {
            //数组
            for (var i in _opt.e_btn) {
                showCustomBtn(_opt.e_btn[i]);
            }
        } else {
            showCustomBtn(_opt.e_btn);
        }
    }

    var showCustomBtn = function (btn) {
        var htm = '<button type="button" class="btn btn-primary">' + btn.txt + '</button>';
        var $htm = $(htm);
        $htm.on('click', function () {
            eval(btn.action + "()");
        });
        $("#im_unique_dlg .modal-footer").append($htm);
    }

    if ($(".form-dialog").length < 1) {
        //不存在，新增一个formDialog
        $('body').append("<div class='form-dialog'></div>");
    }
    init();

    //加载form并显示
    var loadForm = function () {
        ajaxs(_opt.form_url, "get", {id: _opt.id}, true, function (data) {
            $("#im_unique_dlg .modal-body").html(data);
        }, "html");

        $("#im_unique_dlg").modal({
            keyboard: false,
            backdrop: false
        });
    }

    //绑定保存按钮的事件，自定义的form页面必须要实现一个form_sub的js方法，该按钮默认调用此方法
    $(".form-dialog button[save]").on('click', function () {
        //执行提交
        form_sub();
        //关闭自己
        if (_opt.isclose) {
            $("#im_unique_dlg").modal('hide');
        }
        //调用回调函数
        if (_opt.callback) {
            _opt.callback();
        }
    });
    loadForm();
}
$.FormDialg = function (option) {
    var defaultOpt = {
        form_url: '',
        id: 0,
        title: '',
        e_btn: [],          //额外的btn，可选{txt:'123,action:'functionname'}
        callback: null,     //保存成功后的回调函数
        fullscreen: false,
        isclose: false,
        width: '500px'
    }

    var _opt = $.extend({}, defaultOpt, option);

    var init = function () {
        var wdth = _opt.fullscreen ? ' style="width:100%"' : ' style="width:' + _opt.width + '"';
        var htm = '<div class="modal fade" id="im_unique_dlg" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
            '<div class="modal-dialog" ' + wdth + '>' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +
            '<h4 class="modal-title" id="myModalLabel">' + _opt.title + '</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        $(".form-dialog").html(htm);
        //渲染自定义按钮
        if (!_opt.e_btn) {
            return;
        }
        if (Object.prototype.toString.call(_opt.e_btn) == '[object Array]') {
            //数组
            for (var i in _opt.e_btn) {
                showCustomBtn(_opt.e_btn[i]);
            }
        } else {
            showCustomBtn(_opt.e_btn);
        }
    }

    var showCustomBtn = function (btn) {
        var htm = '<button type="button" class="btn btn-primary">' + btn.txt + '</button>';
        var $htm = $(htm);
        $htm.on('click', function () {
            eval(btn.action + "()");
        });
        $("#im_unique_dlg .modal-footer").append($htm);
    }

    if ($(".form-dialog").length < 1) {
        //不存在，新增一个formDialog
        $('body').append("<div class='form-dialog'></div>");
    }
    init();

    //加载form并显示
    var loadForm = function () {
        ajaxs(_opt.form_url, "get", {id: _opt.id}, true, function (data) {
            $("#im_unique_dlg .modal-body").html(data);
        }, "html");

        $("#im_unique_dlg").modal({
            keyboard: false,
            backdrop: false
        });
    }

    //绑定保存按钮的事件，自定义的form页面必须要实现一个form_sub的js方法，该按钮默认调用此方法
    $(".form-dialog button[save]").on('click', function () {
        //执行提交
        form_sub();
        //关闭自己
        if (_opt.isclose) {
            $("#im_unique_dlg").modal('hide');
        }
        //调用回调函数
        if (_opt.callback) {
            _opt.callback();
        }
    });
    loadForm();
}

$.VasFormDialog = function (option) {
    var defaultOpt = {
        form_url: '',
        id: 0,
        title: '',
        e_btn: [],          //额外的btn，可选{txt:'123,action:'functionname'}
        callback: null,     //保存成功后的回调函数
        fullscreen: false,
        isclose: false
    }

    var _opt = $.extend({}, defaultOpt, option);

    var init = function () {
        var wdth = _opt.fullscreen ? ' style="width:100%"' : '';
        var htm = '<div class="modal fade" id="im_unique_dlg" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
            '<div class="modal-dialog" ' + wdth + '>' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +
            '<h4 class="modal-title" id="myModalLabel">' + _opt.title + '</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        $(".form-dialog").html(htm);
        //渲染自定义按钮
        if (!_opt.e_btn) {
            return;
        }
        if (Object.prototype.toString.call(_opt.e_btn) == '[object Array]') {
            //数组
            for (var i in _opt.e_btn) {
                showCustomBtn(_opt.e_btn[i]);
            }
        } else {
            showCustomBtn(_opt.e_btn);
        }
    }

    var showCustomBtn = function (btn) {
        var htm = '<button type="button" class="btn btn-primary">' + btn.txt + '</button>';
        var $htm = $(htm);
        $htm.on('click', function () {
            eval(btn.action + "()");
        });
        $("#im_unique_dlg .modal-footer").append($htm);
    }

    if ($(".form-dialog").length < 1) {
        //不存在，新增一个formDialog
        $('body').append("<div class='form-dialog'></div>");
    }
    init();

    //加载form并显示
    var loadForm = function () {
        ajaxs(_opt.form_url, "get", {id: _opt.id}, true, function (data) {
            $("#im_unique_dlg .modal-body").html(data);
        }, "html");

        $("#im_unique_dlg").modal({
            keyboard: false,
            backdrop: false
        });
    }

    //绑定保存按钮的事件，自定义的form页面必须要实现一个form_sub的js方法，该按钮默认调用此方法
    $(".form-dialog button[save]").on('click', function () {
        //执行提交
        form_sub();
        //关闭自己
        if (_opt.isclose) {
            $("#im_unique_dlg").modal('hide');
        }
        //调用回调函数
        if (_opt.callback) {
            _opt.callback();
        }
    });
    loadForm();
}
var d_locale = {
    format: "YYYY-MM-DD HH:mm:ss", //设置显示格式
    applyLabel: '确定', //确定按钮文本
    cancelLabel: '取消', //取消按钮文本
    customRangeLabel: '自定义',
    daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
    monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
        '七月', '八月', '九月', '十月', '十一月', '十二月'
    ],
    firstDay: 1
}

/**
 * 字典类
 * */
function Dictionary() {
    var items = {};
    this.has = function (key) {
        return key in items;
    };
    this.set = function (key, value) {
        items[key] = value;
    };
    this.delete = function (key) {
        if (this.has(key)) {
            delete items[key];
            return true;
        }
        return false;
    };
    this.get = function (key) {
        return this.has(key) ? items[key] : undefined;
    };
    this.values = function () {
        var values = [];
        for (var k in items) {
            if (this.has(k)) {
                values.push(items[k]);
            }
        }
        return values;
    };
    this.keys = function () {
        return Object.keys(items);
    };
    this.getItems = function () {
        return items;
    };
}

/**
 * 字符串是否是json格式
 * @param str
 * @returns {boolean}
 */
function isJSON(str) {
    if (typeof str == 'string') {
        try {
            var obj = JSON.parse(str);
            if (typeof obj == 'object' && obj) {
                return true;
            } else {
                return false;
            }
        } catch (e) {
            return false;
        }
    }
}

function datetimeFormat_1(longTypeDate) {
    var datetimeType = "";
    var date = new Date();
    date.setTime(longTypeDate);
    datetimeType += date.getFullYear();   //年
    datetimeType += "-" + getMonth(date); //月
    datetimeType += "-" + getDay(date);   //日
    datetimeType += "&nbsp;&nbsp;" + getHours(date);   //时
    datetimeType += ":" + getMinutes(date);      //分
    datetimeType += ":" + getSeconds(date);      //分
    return datetimeType;
}

//返回 01-12 的月份值
function getMonth(date) {
    var month = "";
    month = date.getMonth() + 1; //getMonth()得到的月份是0-11
    if (month < 10) {
        month = "0" + month;
    }
    return month;
}

//返回01-30的日期
function getDay(date) {
    var day = "";
    day = date.getDate();
    if (day < 10) {
        day = "0" + day;
    }
    return day;
}

//返回小时
function getHours(date) {
    var hours = "";
    hours = date.getHours();
    if (hours < 10) {
        hours = "0" + hours;
    }
    return hours;
}

//返回分
function getMinutes(date) {
    var minute = "";
    minute = date.getMinutes();
    if (minute < 10) {
        minute = "0" + minute;
    }
    return minute;
}

//返回秒
function getSeconds(date) {
    var second = "";
    second = date.getSeconds();
    if (second < 10) {
        second = "0" + second;
    }
    return second;
}


/**
 *返回按钮
 */
function goBack() {

    window.history.go(-1);
}

//判空
var ParamEmpty = function (data) {

    if (data === "" || data == null || typeof data === "undefined") {
        return true;
    }

    return false;
};

